import { Modal, Button, Form, InputNumber, Select, message,Table,Input} from 'antd';
import { connect } from 'dva';
import styles from './indexnew.less';
import StockInput from './stockInput';
import {abs} from '@/utils/utils';

const FormItem = Form.Item;
const Option = Select.Option;

@Form.create()
class ChangeMProductPrice extends React.Component {

    constructor(props) {
        super(props);
        this.state= {
            columns: [],
            btnLoading: false,
            MemberPrices:[]
        }
    }

    componentWillMount() {
        window.Isoption = false;
      }
      componentDidMount() {
        window.Isoption = true;
      }

    handleOk = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editMPriceVisible: false }, () => {
            this.forceUpdate();
        });
    };

    handleCancel = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editMPriceVisible: false }, () => {
            this.forceUpdate();
        });
    };

    // 取消
    clickCancel =() => {
        this.setState({
            allValue: '',
        })
        this.handleCancel();
    }

    //单个确认
    changePriceBtnSingle =(e) => {
        e.preventDefault();
        const {form, dispatch, ProductId, MemberPriceByProduct, _thisInSale,_thisInStock,_thisSoldOut} = this.props;
        form.validateFields((err, values) => {
            if(!err) {
                const MemberPrices = MemberPriceByProduct&&MemberPriceByProduct.data.SingleSkuInfo[0].MemberPrices;
                this.setState({
                  btnLoading: true
              })
                dispatch({
                    type: 'pruductSellList/UpdateMProductPrice',
                    payload: {
                        ProductId: ProductId,
                        ProductSku: [{
                            SkuId: ProductId,
                            MemberPrices: MemberPrices
                        }]
                    },
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('修改成功');
                            this.handleOk();
                            if(_thisInSale) {
                                _thisInSale.GetSellProductList();
                            }
                            if(_thisInStock) {
                                _thisInStock.getSearchWarehouseProductListWithPage();
                            }
                            if(_thisSoldOut) {
                               _thisSoldOut.getSearchSoldOutProductListWithPage();
                            }
                            this.setState({
                                allValue: '',
                                btnLoading: false
                            })
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                          this.setState({ btnLoading: false });
                        },
                    },
                })
            }
        })
    }

    // 确认
    changePriceBtn =(e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) =>{
            if(!err) {
                const {  _thisInSale, _thisInStock,_thisSoldOut,dispatch, ProductId, MemberPriceByProduct} = this.props;
                const ProductSku = [];
                MemberPriceByProduct&&MemberPriceByProduct.data.SkuList.map((item, index)=> {
                    var obj={};
                    obj.SkuId=item.skuId;
                    obj.MemberPrices=item.MemberPrices;
                    ProductSku.push(obj)
                })
                this.setState({
                  btnLoading: true
              })
                dispatch({
                    type: 'pruductSellList/UpdateMProductPrice',
                    payload: {
                        ProductId: ProductId,
                        ProductSku: ProductSku
                    },
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('修改成功');
                            this.handleOk();
                            if(_thisInSale) {
                                this.props._thisInSale.GetSellProductList();
                            }
                            if(_thisInStock) {
                                this.props._thisInStock.getSearchWarehouseProductListWithPage();
                            }
                            if(_thisSoldOut) {
                                this.props._thisSoldOut.getSearchSoldOutProductListWithPage();
                            }
                            this.setState({
                                allValue: '',
                                btnLoading: false
                            })
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                          this.setState({ btnLoading: false });
                        },
                    },
                })
            }
        })
    }

    getAllInputValue =(value) => {
        this.setState({
            allValue: value,
        })
    }

    getInputValue =(e, index) => {
    const {dispatch} = this.props;
    const sourceDatas = this.props.MemberPriceByProduct.data.SingleSkuInfo;
    sourceDatas[0].MemberPrices[index].MemberPrice = e;
    dispatch({
        type:'pruductSellList/changeSangelData',
        payload:sourceDatas,
        callBack:{
            success:(res)=>{
                this.forceUpdate();
            }
        }
    })
  }

    // 保存
    clickSetOnTime =() => {
        this.props.form.validateFields((error) =>{
            if(!error) {
                const { allValue, selectCard} = this.state;
                const {dispatch} = this.props;
                const sourceDatas = this.props.MemberPriceByProduct.data.SkuList;
                sourceDatas.map((item, index) => {
                    let cardIndex = item.MemberPrices.findIndex(vel => vel.CardId===selectCard);
                    cardIndex> -1?item.MemberPrices[cardIndex].MemberPrice =allValue:''
                })
                dispatch({
                    type:'pruductSellList/changeSangelData',
                    payload:sourceDatas,
                    callBack:{
                        success:(res)=>{
                            this.forceUpdate();
                        }
                    }
                })
            }
        })
    }

    clickSetOnTimeout=()=> {
        const {dispatch} = this.props;
        const sourceDatas = this.props.MemberPriceByProduct.data.SkuList;
        sourceDatas.map((item, index)=> {
            item.MemberPrices.map((vel, i) => {
                vel.MemberPrice = ''
            })
        })
        dispatch({
            type:'pruductSellList/changeSangelData',
            payload:sourceDatas,
            callBack:{
                success:(res)=>{
                    this.forceUpdate();
                    message.success('清除设置')
                }
            }
        })
    }

    checkBlur = (id) => {
        this.props.form.validateFields([id], { force: true });
    }

    changeAllPrice =(e, colIndex, rowIndex) => {
        const {dispatch} = this.props;
        const sourceDatas = this.props.MemberPriceByProduct.data.SkuList;
        sourceDatas[colIndex].MemberPrices[rowIndex].MemberPrice = e;
        dispatch({
            type:'pruductSellList/changeSangelData',
            payload:sourceDatas,
            callBack:{
                success:(res)=>{
                    this.forceUpdate();
                }
            }
        })
    }

    selectChange=(value)=> {
        this.setState({
            selectCard: value
        })
    }

    render() {
        const {editMPriceVisible, _this, MemberPriceByProduct, ProductId, gradeCard} = this.props;
        const cardList = MemberPriceByProduct&&MemberPriceByProduct.data?MemberPriceByProduct.data.CardList:[]; //卡片
        const skuData = MemberPriceByProduct&&MemberPriceByProduct.data?MemberPriceByProduct.data.SkuList:[]; //多个
        const singleSkuInfo = MemberPriceByProduct&&MemberPriceByProduct.data?MemberPriceByProduct.data.SingleSkuInfo:[]; //单个
        const X = 160* cardList.length;
        const {getFieldDecorator} = this.props.form;
        const {btnLoading, columns} = this.state;
        const formItemLayout = {
          labelCol: {
            span: 4 ,
          },
          wrapperCol: {
            span: 16 ,
          },
        };



        const columnsfalse = [
            {
                title: '正常售价',
                width: 100,
                key: 'SalePrice',
                align: 'center',
                fixed: 'left',
                render: (test, row, index)=> {
                  return <span>{'￥'+abs(row.SalePrice, 2)}</span>
                }
            },
        ]
        cardList&&cardList.forEach((item, index) => { //单个
            columnsfalse.push({
                title: item.Name,
                key: item.Id,
                width: 160,
                align: 'center',
                render: ()=> {
                    return (
                        <FormItem style={{ marginBottom: 0 }} key={index}>
                            {this.props.form.getFieldDecorator('price' + index, {
                                initialValue:singleSkuInfo[0].MemberPrices[index].MemberPrice,
                                rules: [
                                    {required: false,message: ' '},
                                    {pattern: /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: ' '},
                                ]
                            })(
                                <span>
                                    <StockInput
                                      min={0}
                                      max={singleSkuInfo[0].SalePrice}
                                      // style={{width: '100%'}}
                                      onChange={e => this.getInputValue(e,index)}
                                      setValue={singleSkuInfo[0].MemberPrices[index].MemberPrice}
                                  />
                                  <span style={{marginLeft: 4}}>元</span>
                                </span>

                            )}
                        </FormItem>
                    )
                }
            })
        })


        //******//
        const data = skuData;
        let skuList=[];
        let rex1=/^k[0-9]*$/gi;
        if (data&&data.length> 0) {
            Object.keys(data[0]).forEach(function(key){
                if(key.match(rex1)){
                    var sid=key.replace("k","");
                    let item={ 
                        id: data[0]["k"+sid+"_id"],
                        name:data[0][key]
                    };
                    if(item.id){
                        skuList.push(item);
                    }      
                    
                }
           });
        }
        skuList.push(
            { id:0, name:'正常售价' }
        );

        let g1=0;
        let g2=0;
        let g3=0;
        const columnsData = [];
        skuList.forEach((item, itemIndex) => {
            let dataIndex="v1";
            let width = 0;
            let align = 'center';
            if(skuList.length=== 4) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = 100
                }
                if(itemIndex===1){
                    dataIndex="v2";
                    width = 100
                }
                 if(itemIndex===2){
                    dataIndex="v3";
                    width = 100
                }
                if (itemIndex===3){
                    dataIndex="price";
                    width = 100
                }
            }
            if(skuList.length=== 3) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = 100
                }
                if(itemIndex===1){
                    dataIndex="v2";
                    width = 100
                }
                 if(itemIndex===2){
                    dataIndex="price";
                    width = 100
                }
            }
            if(skuList.length=== 2) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = 100
                }
                if(itemIndex===1){
                    dataIndex="price";
                    width = 100
                }
            }

            let col = {
                title: item.name,
                dataIndex: dataIndex,
                width:  width,
                align: align,
                fixed: 'left',
                render: (text, row, index) => {
                    const obj = {
                        children: text,
                        props: {},
                    };
                    if (skuList.length=== 4) {
                        if(itemIndex===0){
                            if(row.v1_id!==g1){
                                obj.props.rowSpan = row.row_1_num;
                                g1=row.v1_id;
                                g2=0;
                                g3=0;
                            }
                            else{
                                obj.props.rowSpan=0;
                            }
                         }
                         if(itemIndex===1) {
                            if(row.v2_id!==g2){
                                obj.props.rowSpan = row.row_2_num;
                                g2=row.v2_id;
                                g3=0;
                            }else{
                                obj.props.rowSpan=0;
                            }
                         }
                         if(itemIndex===2) {
                            if(row.v3_id!==g3){
                                obj.props.rowSpan = row.row_3_num;
                                g3=row.v3_id;
                            }else{
                                obj.props.rowSpan=0;
                            }
                         }
                         if (itemIndex===3){
                            return (
                              <span>{'￥'+abs(row.price, 2)}</span>
                            )
                         }
                      } if (skuList.length=== 3) {
                        if(itemIndex===0){
                            if(row.v1_id!==g1){
                                obj.props.rowSpan = row.row_1_num;
                                g1=row.v1_id;
                                g2=0;
                                g3=0;
                            }
                            else{
                                obj.props.rowSpan=0;
                            }
                         }
                         if(itemIndex===1) {
                            if(row.v2_id!==g2){
                                obj.props.rowSpan = row.row_2_num;
                                g2=row.v2_id;
                                g3=0;
                            }else{
                                obj.props.rowSpan=0;
                            }
                         }
                          if (itemIndex===2){
                            return (
                                <span>{'￥'+abs(row.price, 2)}</span>
                            )
                         }
                      } if (skuList.length=== 2) {
                          if(itemIndex===0){
                              if(row.v1_id!==g1){
                                  obj.props.rowSpan = row.row_1_num;
                                  g1=row.v1_id;
                              }
                              else{
                                  obj.props.rowSpan=0;
                              }
                           }
                          if (itemIndex===1){
                              return (
                                <span>{'￥'+abs(row.price, 2)}</span>
                              )
                           }
                      }
                      return obj;
                }
            }
            columnsData.push(col)
        })

        cardList&&cardList.forEach((item, eIndex) => {
            columnsData.push({
                title: item.Name,
                key: item.Id,
                align: 'center',
                width: 160,
                render: (record, row, index)=> {
                    return (
                        <FormItem style={{ marginBottom: 0 }} key={index}>
                            {this.props.form.getFieldDecorator('price' + eIndex + index, {
                                initialValue:skuData[index].MemberPrices[eIndex].MemberPrice,
                                rules: [
                                    {required: false, message: ' '},
                                    {pattern: /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: ' '},
                                ]
                            })(
                              <span>
                                  <StockInput
                                    min={0}
                                    max={row.price}
                                    onChange={e=> this.changeAllPrice(e, index, eIndex)}
                                    setValue={skuData[index].MemberPrices[eIndex].MemberPrice}
                                    
                                  />
                                  <span style={{marginLeft: 4}}>元</span>
                                </span>
                            )}
                        </FormItem>
                    )
                }
            })
        })

        return (
            <div>
                <Modal
                    visible={editMPriceVisible}
                    title="自定义会员价"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={null}
                    width={800}
                    className={styles.form}
                >
                    {MemberPriceByProduct&&MemberPriceByProduct.data&&!MemberPriceByProduct.data.IsMultiSku?
                    <Form>
                        <div className={styles.modalTableContent}>
                            <div>
                                <div style={{marginBottom:8}}>
                                    商品名称: {MemberPriceByProduct&&MemberPriceByProduct.data&&MemberPriceByProduct.data.ProductName}
                                </div>
                                <Table
                                    bordered
                                    columns={columnsfalse}
                                    dataSource={MemberPriceByProduct&&MemberPriceByProduct.data&&MemberPriceByProduct.data.SingleSkuInfo}
                                    pagination={false}
                                    scroll={{ x: X + 100}}
                                    rowKey ={() => Math.random()*10}
                                />
                            </div>
                        </div>
                        <div className={styles.footerLineMprice} style={{justifyContent: 'flex-end'}}>
                            <div>
                                <Button onClick={this.clickCancel}>取消</Button>
                                <Button
                                  type="primary"
                                  style={{marginLeft: 8}}
                                  onClick ={this.changePriceBtnSingle}
                                  loading={btnLoading}
                                >确认</Button>
                            </div>
                        </div>
                    </Form>:( //多规格
                        <Form>
                        <div className={styles.modalTableContent}>
                            <div>
                                <div style={{marginBottom:8}}>
                                    商品名称:{MemberPriceByProduct&&MemberPriceByProduct.data&&MemberPriceByProduct.data.ProductName}
                                </div>
                                <Table
                                    bordered
                                    rowKey ={() => Math.random()*20}
                                    columns={columnsData}
                                    dataSource={MemberPriceByProduct&&MemberPriceByProduct.data&&MemberPriceByProduct.data.SkuList}
                                    pagination={false}
                                    scroll={{  x: X + skuList.length*100, y:300}}
                                    onRow={(record) => {
                                        return {
                                          onClick: (event) => {},       // 点击行
                                          onDoubleClick: (event) => {},
                                          onContextMenu: (event) => {},
                                          onMouseEnter: (event) => {},  // 鼠标移入行
                                          onMouseLeave: (event) => {},
                                          onBlur:()=>{}
                                        };
                                      }}
                                />
                            </div>
                        </div>
                        <div className={styles.footerLineMprice}>
                            <FormItem label="批量设置" {...formItemLayout}>
                                <Select style={{marginRight: 8, width: 128}} onChange={this.selectChange}>
                                    {cardList&&cardList.map((item, index)=> {
                                        return <Option value={item.Id} key={index}>{item.Name}</Option>
                                    })}
                                </Select>
                                <FormItem>
                                    {getFieldDecorator('numbers', {
                                        rules: [
                                        {required: false, message: ''},
                                        {pattern: /^([1-9]\d*|[0]{1,1})$/, message: '不小于0整数'}
                                    ]
                                })(
                                    <span className={styles.inputBox}>
                                        <InputNumber
                                            placeholder=""
                                            min={0} max={999999}
                                            value={this.state.allValue}
                                            onChange={e => this.getAllInputValue(e)}
                                        />
                                        <a
                                        href="javascript:;"
                                        style={{width: '3em', marginLeft: 8}}
                                        onClick={() => this.clickSetOnTime()}>
                                            保存
                                        </a>
                                        <a
                                        href="javascript:;"
                                        style={{width: '3em', marginLeft: 8}}
                                        onClick={() => this.clickSetOnTimeout()}>
                                            取消
                                        </a>
                                    </span>
                                )}
                               </FormItem>
                            </FormItem>
                            <div>
                                <Button onClick={this.clickCancel}>取消</Button>
                                <Button
                                  type="primary"
                                  style={{marginLeft: 8}}
                                  onClick ={this.changePriceBtn}
                                  loading={btnLoading}
                                >确认</Button>
                            </div>
                        </div>
                        </Form>
                    )}
                </Modal>
            </div>
        )
    }
}

export default connect(({pruductSellList, global, loading}) => ({
    MemberPriceByProduct:pruductSellList.MemberPriceByProduct?pruductSellList.MemberPriceByProduct:{}
}))(ChangeMProductPrice)
